/**
 * item mapper
 * @author wuji
 * @date 2020-07-19
 */
const {db} = require("../db/db.js");

/**
 * Select All Items
 */
exports.selectAllItem = function(cb) {
    db.all("select id, name, url, content, pid as pId, orders from tb_item order by orders", cb);
}

/**
 * Select First
 */
exports.selectFirstItem = function(cb) {
    db.all("select id, name, url, content, pid as pId, orders from tb_item limit 1", cb);
}

/**
 * Select Item By Id
 * @param {*} id 
 */
exports.selectItemById = function(id, cb) {
    db.all("select id, name, url, content, pid as pId, orders from tb_item where id = ?", id, cb);
}

/**
 * Add Item
 * @param {*} item 
 */
exports.addItem = function(item, cb) {
    db.run("insert into tb_item (name, url, content, pid, orders) values (?,?,?,?,?)",
        [item.name, item.url, item.content, item.pId, item.orders], cb);
}

/**
 * Delete Item By Id
 * @param {*} id 
 */
exports.deleteItemById = function(id, cb) {
    db.run("delete from tb_item where id = ?", id, cb);
}

/**
 * Delete All Items Of The Company
 * @param {*} cId 
 */
exports.deleteItemsByCompanyId = function(cId, cb) {
    db.run("delete from tb_item where pid in (select id from tb_project where cid = ?)", cId, cb);
}

/**
 * Delete All Items Of The Project
 * @param {*} cId 
 */
 exports.deleteItemsByProjectId = function(pId, cb) {
    db.run("delete from tb_item where pid = ?", pId, cb);
}

/**
 * Update Item
 * @param {*} item 
 */
exports.updateItem = function(item, cb) {
    db.run("update tb_item set name = ?, url = ?, content = ?, pid = ?, orders = ? where id = ?", 
        [item.name, item.url, item.content, item.pId, item.orders, item.id], cb);
}

/**
 * Update Items
 * @param {*} item 
 */
exports.updateItems = function(items, cb) {
    db.serialize(() => {
        db.run("begin");

        const statement = db.prepare("update tb_item set content = ? where id = ? ");
        for (var i = 0, len = items.length; i < len; i++) {
            statement.run(items[i].content, items[i].id)
        }

        db.run("commit");
        statement.finalize((err) =>{
            cb(err)
        })
    })
}